package org.ronghao.androidwifiplatfrom.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.ronghao.androidwifiplatfrom.utils.Contants;

import android.util.Log;

public class SocketClient extends Thread {
	private String IP;
	private String msg;
	private Socket socket;

	public SocketClient(String ip, String msg) {
		this.IP = ip;
		this.msg = msg;
	}
	
	/**
	 * 关闭socket
	 * @author ronghao
	 * @data 2012-11-30    下午2:54:42
	 */
	public void close(){
		if (socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public synchronized void run() {
		try {
			// 建立Socket服务，指定要链接主机和端口。
			socket = new Socket(IP,
					Contants.SERVER_HOST_PORT);
			// 获取Socket流中的输出流，将数据写到该流中。通过网络发送给服务端。
			OutputStream out = socket.getOutputStream();
			// 获取Socket流中的输入流，将服务端反馈的数据获取到并打印
			BufferedReader input = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			// 注意第二个参数据为true将会自动flush，否则需要需要手动操作out.flush()
			PrintWriter output = new PrintWriter(out, false);

			output.write(msg);
			output.flush();

			char[] buf = new char[1024];
			int len = input.read(buf);// 阻塞

			Log.d("Tcp Demo", "message From Server:" + new String(buf, 0, len));
			// 关闭客户端资源
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
